package ljl.codetop300;

import commons.ListNode;

public class _02_05_add_two_nums {

  static class test {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      int carry = 0;
      ListNode p = l1, q = l2;
      ListNode head = new ListNode();
      ListNode cur = head;
      while (p != null || q != null) {
        int v1 = p == null ? 0 : p.val;
        int v2 = q == null ? 0 : q.val;
        int sum = v1 + v2 + carry;
        cur.next = new ListNode(sum % 10);
        carry = sum / 10;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
        cur = cur.next;
      }
      if (carry != 0) {
        cur.next = new ListNode(carry);
      }
      return head.next;
    }
  }
}
